import { Injectable } from '@nestjs/common';
import { SpecsType_Create_Dto, SpecsType_Update_Dto } from './assets/specsType.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { SpecsType } from './assets/specsType.entity';
import { Repository } from 'typeorm';
import { SpecsType_FindByPage_Dto } from './assets/specsType.dto';
import {
  util_Db_PageList,
  util_Db_NoPageList,
  util_Db_Add,
  util_Db_Update,
  util_Db_Delete,
} from '@/common/util/db';
import { Platform_Service } from '../platform/platform.service';

@Injectable()
export class SpecsType_Service {
  constructor(
    @InjectRepository(SpecsType)
    private specsType_Repository: Repository<SpecsType>,
    private platform_Service: Platform_Service,
  ) {}

  async specsType_Create(body: SpecsType_Create_Dto) {
    const platForm = await this.platform_Service.platform_FindOneById(body.platFormId);
    return await util_Db_Add({
      createDto: { ...body, platForm },
      repository: this.specsType_Repository,
    });
  }

  async specsType_FindAll(query: SpecsType_FindByPage_Dto) {
    return await util_Db_NoPageList<SpecsType>({
      queryBuilder: this.specsType_Repository.createQueryBuilder('specsType'),
      query: {
        'specsType.platFormId': query.platFormId,
      },
    });
  }

  async specsType_FindByPlatFormId(platFormId: number) {
    return await util_Db_PageList({
      queryBuilder: this.specsType_Repository
        .createQueryBuilder('specsType')
        .leftJoinAndSelect('specsType.specs', 'specs'),
      query: { 'specsType.platFormId': platFormId },
    });
  }

  async specsType_Update(body: SpecsType_Update_Dto) {
    return await util_Db_Update({
      findOne: () => this.specsType_FindOneById(body.id),
      updateDto: body,
      repository: this.specsType_Repository,
    });
  }

  async specsType_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.specsType_FindOneById(id),
      id,
      repository: this.specsType_Repository,
    });
  }

  async specsType_FindOneById(id: number) {
    return await this.specsType_Repository
      .createQueryBuilder('specsType')
      .andWhere(`specsType.id = :id`, { id: id })
      .getOne();
  }
}
